import { App, Button, Input } from 'antd';
import { useMemo, useRef, useState } from 'react';
import type {
  ActionRefType,
  YmEditTableColumnType,
  YmEditTableProps,
} from 'ym-design';
import { YmEditTable } from 'ym-design';

type RecordType = {
  editRowKey?: string | number;
  name?: string;
  age?: number;
  ageRange?: any[];
  birthDay?: any;
  dateRange?: any;
  favorite?: string[];
  study?: string[];
  sleepDuration?: any;
  marke?: string;
  customer?: string;
};

function BasicEditTable() {
  const { message } = App.useApp();
  const editTableRef = useRef<ActionRefType<RecordType>>(null);
  const [values, setValues] = useState<RecordType[]>([]);
  const columns = useMemo<YmEditTableColumnType<RecordType>[]>(
    () => [
      {
        key: 'name',
        dataIndex: 'name',
        title: '姓名',
        editable: true,
        valueType: {
          type: 'input',
          inputProps: {
            placeholder: '请输入',
            autoComplete: 'off',
          },
        },
        formItemProps: {
          rules: [
            { required: true, message: '请输入姓名' },
            {
              min: 2,
              max: 6,
              whitespace: true,
              message: '请输入2-6个中文字符',
            },
          ],
        },
      },
      {
        key: 'age',
        dataIndex: 'age',
        title: '年龄',
        editable: true,
        valueType: {
          type: 'inputNumber',
          inputNumberProps: {
            placeholder: '请输入年龄',
            autoComplete: 'off',
          },
        },
        formItemProps: {
          rules: [
            { required: true, message: '请输入年龄' },
            {
              min: 10,
              max: 60,
              type: 'number',
              message: '请输入10-60之间的数字',
            },
          ],
        },
      },
      {
        key: 'ageRange',
        dataIndex: 'ageRange',
        title: '年龄区间',
        editable: true,
        valueType: {
          type: 'inputRange',
          inputRangeProps: {
            placeholder: '请输入',
            autoComplete: 'off',
          },
        },
        formItemProps: {
          messageVariables: { displayName: '年龄区间' },
          rules: [
            // { required: true, whitespace: true, message: '请输入年龄区间' },
            {
              validator(rule, value) {
                if (
                  (Array.isArray(value) && (!value[0] || !value[1])) ||
                  !value
                ) {
                  return Promise.reject('${displayName} 每一项不得为空');
                } else if (
                  Array.isArray(value) &&
                  value[0] &&
                  value[1] &&
                  Number(value[0]) >= Number(value[1])
                ) {
                  return Promise.reject(
                    '${displayName} 前一项的值必须小于后一项',
                  );
                }
                return Promise.resolve();
              },
            },
          ],
        },
      },
      {
        key: 'birthDay',
        dataIndex: 'birthDay',
        title: '生日',
        editable: true,
        valueType: {
          type: 'date',
          datePickerProps: {
            placeholder: '请选择',
          },
        },
        formItemProps: {
          rules: [{ required: true, message: '请选择生日' }],
        },
      },
      // {
      //   key: 'dateRange',
      //   dataIndex: 'dateRange',
      //   title: '日期区间',
      //   editable: true,
      //   valueType: {
      //     type: 'rangeDate',
      //     rangePickerProps: {
      //       placeholder: ['请选择', '请选择']
      //     }
      //   }
      // },
      // {
      //   key: 'favorite',
      //   dataIndex: 'favorite',
      //   title: '兴趣爱好',
      //   editable: true,
      //   valueType: {
      //     type: 'select',
      //     selectProps: {
      //       options: [
      //         { label: '敲代码', value: 'code' },
      //         { label: '健身', value: 'sports' },
      //         { label: '做饭', value: 'cooking' },
      //         { label: '乒乓球', value: 'pingpongball' },
      //       ]
      //     }
      //   },
      //   formItemProps: {
      //     rules: [
      //       { required: true, message: '请选择兴趣爱好' }
      //     ]
      //   }
      // },
      // {
      //   key: 'study',
      //   dataIndex: 'study',
      //   title: '学习课程',
      //   editable: true,
      //   valueType: {
      //     type: 'checkbox',
      //     checkboxGroupProps: {
      //       options: [
      //         { label: '数学', value: 'maths' },
      //         { label: '语文', value: 'chinese' },
      //         { label: '英语', value: 'english' }
      //       ]
      //     }
      //   },
      //   formItemProps: {
      //     rules: [
      //       { required: true, message: '请选择学习课程' }
      //     ]
      //   }
      // },
      // {
      //   key: 'sleepDuration',
      //   dataIndex: 'sleepDuration',
      //   title: '睡觉时间点',
      //   editable: true,
      //   valueType: {
      //     type: 'radio',
      //     radioGroupProps: {
      //       options: [
      //         { label: '10点', value: '10' },
      //         { label: '11点', value: '11' },
      //         { label: '12点', value: '12' },
      //       ]
      //     }
      //   },
      //   formItemProps: {
      //     rules: [
      //       { required: true, message: '请选择睡觉时间点' }
      //     ]
      //   }
      // },
      {
        key: 'marke',
        dataIndex: 'marke',
        title: '备注',
        editable: true,
      },
      {
        key: 'customer',
        dataIndex: 'customer',
        title: '自定义组件项',
        editable: true,
        valueType: (form, record, { value, onChange }) => {
          return (
            <Input
              value={value}
              autoComplete="off"
              onChange={(e) => {
                console.log('--form--allValues--:', form.getFieldsValue('all'));
                const newMarke = `${e.target.value}备注`;
                form.setFieldValue('marke', newMarke);
                onChange(e);
              }}
            />
          );
        },
        formItemProps: {
          rules: [{ required: true, message: '自定义组件项不得为空' }],
        },
      },
      {
        key: 'operation',
        dataIndex: 'operation',
        title: '操作',
      },
    ],
    [],
  );

  const ymEditTableConfig: YmEditTableProps = {
    value: values,
    onRowValuesChange(rowIndex, newRecord) {
      console.log(
        '--onRowValuesChange--rowIndex--newRecord--:',
        rowIndex,
        newRecord,
      );
    },
    onChange(newValues) {
      console.log('--onChange--newValues--:', newValues);
      setValues(newValues);
    },
    columns,
    max: 3,
  };

  //提交
  const handleSub = () => {
    editTableRef.current
      ?.handleValidate()
      .then((values) => {
        console.log('--values--:', values);
      })
      .catch((errors) => {
        console.log('--errors--:', errors);
      });
  };

  //重置
  const handleReset = () => {
    editTableRef.current?.handleReset();
  };

  const handleSetRowsData = () => {
    const currRowData = values[0];
    if (!currRowData) return message.error('请先添加第一行数据');
    if (
      currRowData &&
      (currRowData.editRowKey === undefined || currRowData.editRowKey === null)
    )
      return message.error('数据有误');
    currRowData.name = '11111';
    editTableRef.current?.setRowsData(currRowData);
  };

  return (
    <div>
      <p>
        <Button onClick={handleSub}>提交</Button>
        <Button onClick={handleReset}>重置</Button>
        <Button onClick={handleSetRowsData}>设置第一行数据</Button>
      </p>
      <YmEditTable {...ymEditTableConfig} ref={editTableRef} />
    </div>
  );
}

export default BasicEditTable;
